import { Form, Input, Row,TreeSelect} from 'antd';
import React, { Component } from 'react';
import { isEmpty, isFunction,isArray } from 'lodash';
import {  createForm } from '/common/components/HocCRUD';
import { recursiveFind } from '/common/utils/ArrayUtils';
import ModalComp from '/common/components/ModalItem/ModalComp';

@Form.create()
@createForm()
class DetailForm extends Component {

    constructor(props) {
        super(props);
        this.state = {};
    }

    getAjaxData() {
        const { compData = {} } = this.props;
        return new Promise((resolve, reject) => {
            this.props.form.validateFieldsAndScroll(async (errors, fieldsValue) => {
                if (isEmpty(errors)) {
                    const values = {
                        ...fieldsValue
                    };
                    compData.id > 0 && (values.id = compData.id);
                    let parent = recursiveFind(this.props.dirCompData,(obj)=>{
                      return obj.id === values.parentId;
                    });
                    if(parent){
                      values['parentIsn'] = parent['isn'];
                      delete values['parentId'];
                    }
                    resolve(values);
                } else {
                    reject(errors);
                }
            });
        });
    }

    getFields(formFields) {
        const formProps = {
            labelCol: { span: 7 },
            wrapperCol: { span: 12 },
        };
        const colSpan = 0;
        return this.props.getFields(formFields, colSpan, formProps);
    }

    selectTree(list) {
      // return false;

        const loop = (data,disableds) => data.map((item) => {
            let disabled = false;
            if(!isEmpty(this.props.compData)&&this.props.compData.id>0){
                  if(item.id === this.props.compData.id){
                    disabled = true;
                  }else{
                    disabled = disableds;
                  }
            }
            if (item.children && item.children.length) {
                return <TreeSelect.TreeNode disabled={disabled}
                                            value={item.id}
                                            title={item.name}
                                            key={item.id}>{loop(item.children,disabled)}</TreeSelect.TreeNode>;
            }
            return <TreeSelect.TreeNode disabled={disabled}
                                        value={item.id}
                                        title={item.name}
                                        key={item.id}/>;
        });
        return (
            <TreeSelect
                placeholder="请选择目录"
                treeDefaultExpandAll
                onChange={this.onChange}
            >
              <TreeSelect.TreeNode
                                   value={''}
                                   title={'请选择'}
                                   key={0}/>
                {loop(list)}
            </TreeSelect>
        );
    }

    render() {
        const { compData,dirCompData } = this.props;

        let parentId='';
        if(!isEmpty(compData)){
          if(compData.id > 0&&compData.parentIsn){
           let parent = recursiveFind([...dirCompData],obj=>{
              return obj.isn ==  compData.parentIsn;
            });
            parent&&(parentId = parent.id);
          }
        }else{
          if(isArray(this.props.selectedDirKeys)&&this.props.selectedDirKeys.length>0){
              parentId = this.props.selectedDirKeys[0];
          }
        }
        let selectComp = this.selectTree(dirCompData);

        const formFields = [
            {
                label: '文件夹名称',
                fieldName: 'name',
                options: {
                    initialValue: compData?compData.name:'',
                    rules: [{
                        required: true,
                        message: '请输入文件夹名称',
                    }],
                },
                comp:  <Input placeholder={`请输入文件夹名称`}/>,
            },
            {
               label: '所属目录',
               fieldName: 'parentId',
               options: {
                 initialValue:parentId,
                 rules: [],
               },
               comp: selectComp,
            }
        ];
        return (
            <>
            <Form layout="horizontal">
                <Row gutter={16}>
                    {this.getFields(formFields)}
                </Row>
            </Form>
            </>
        );
    }
}

class FolderDetail extends React.Component {
    constructor(props) {
        super(props);
        this.state = {};
        this.itemRef = React.createRef();
    }

    componentDidMount(){}

    async handleOk() {
        const {
            saveDetail
            } = this.props;
        const itemRef = this.itemRef.current;
        if (itemRef && isFunction(itemRef.getAjaxData)) {
            try {
                const values = await itemRef.getAjaxData();
                saveDetail(values);
                this.porps.hideDetail();
            } catch (e) {
                // console.log(e);
            }

        } else {
            console.error('EmployeeClassifyDetail Have not getAjaxData function');
        }
    };

    handleCancel(e) {
        this.props.hideDetail();
    }

    render() {
        const { compData } = this.props;
        const isEdit = (compData && compData.id > 0);

        // console.log('selectedDirKeys:',this.props.selectedDirKeys);
        return (
            <ModalComp
                width={520}
                // key={Math.round()}
                title={`${isEdit?'编辑':'新建'}文件夹`}
                visible={this.props.isShowDetail}
                onOk={this.handleOk.bind(this)}
                onCancel={this.handleCancel.bind(this)}
                destroyOnClose={true}
            >
                <DetailForm compData={compData}
                            dirCompData={this.props.dirComp}
                            key={`folder_form_${Math.random()}`}
                            fromLineLeg={5}
                            selectedDirKeys={this.props.selectedDirKeys}
                            wrappedComponentRef={this.itemRef}/>
            </ModalComp>)
    }
}

FolderDetail.defaultProps = {
  selectedDirKeys:[]
};

export default FolderDetail;



